<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>标签管理</el-breadcrumb-item>
      <el-breadcrumb-item>标签-地图</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>

<el-row :gutter="35">

        <el-col :span="3">
          <el-button type="primary" @click="handleAddNewLabel ()" icon="el-icon-search"
            >加入新标签</el-button
          >
        </el-col>

          <el-col :span="8">
          <el-date-picker
      v-model="timeRange"
      type="datetimerange"
      range-separator="至"
      start-placeholder="筛选开始时间"
      end-placeholder="筛选结束时间">
          </el-date-picker>
        </el-col>

        <el-col :span = "3">
          <el-select v-model="selecttype">
            <el-option v-for="ftypes in typelist" 
            :label="ftypes" 
            :key="ftypes"
            :value="ftypes"/>
          </el-select>
        
        </el-col>

        <el-col :span = "3">
          <el-select v-model="selectpass">
            <el-option v-for="fpass in passlist" 
            :label="fpass" 
            :key="fpass"
            :value="fpass"/>
          </el-select>
        
        </el-col>

        
            <el-col :span="4">
          <el-input
            placeholder="地点搜索"
            v-model="selectaddress"
            clearable
            @clear=""
            @click=""
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search()"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>
<el-divider></el-divider>
     
        <div :style="{width:'90%',height:'500px',margin: '0 auto'}" class="amap-page-container">
           <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>

            <el-amap vid="amap" :plugin="plugin" 
            class="amap-demo" :center="center"
            :zoom="zoom" :events="events"
            >
            
   <el-amap-marker v-for="marker in markers" :position="marker.position"  :events="marker.events"></el-amap-marker>
    <el-amap-info-window v-if="window" :position="window.position" :visible="window.visible" :content="window.content"></el-amap-info-window>
 
      </el-amap>
      </div>

 
    </el-card>

    <el-dialog title="添加新标签" :visible.sync="newDialogVisible" width="50%">
    <el-row :gutter="20">
           <el-col :span="4">
        <label for="point">地点坐标:</label>
                    </el-col>
            <el-col :span="16">
        <label >{{newpoint}}
          </label>
     </el-col>
       </el-row>

    <el-row :gutter="20">
           <el-col :span="4">
        <label for="answer">地点位置:</label>
                    </el-col>
            <el-col :span="16">
        <label >{{newaddress}}
          </label>
            </el-col>
            </el-row>


    <el-row :gutter="20">
           <el-col :span="4">
        <label for="answer">路况类型:</label>
                    </el-col>
            <el-col :span="16">
        <el-select v-model="newtype">
            <el-option v-for="ntype in typelist" 
            :label="ntype" 
            :key="ntype"
            :value="ntype"/>
          </el-select>
            </el-col>
            </el-row>

            <el-row :gutter="10">

              <el-row :gutter="20">
           <el-col :span="4">
        <label for="answer">通行情况:</label>
                    </el-col>
            <el-col :span="4">

	    <el-button :class="[flag===0?yes:no]" @click="chooseEmer(0)">{{pass1}}</el-button>
      </el-col>
      <el-col :span="4">
	    <el-button :class="[flag===1?yes:no]" @click="chooseEmer(1)">{{pass2}}</el-button>

            </el-col>
            </el-row>

      <el-row :gutter="20">
           <el-col :span="6">
        <label for="point">提醒其他人需要注意前方路况的时间:</label>
                    </el-col>
            <el-col :span="4">
        <el-input v-model="newtime" placeholder='0'>
          </el-input>
          </el-col>
          <el-col :span="4">
        <label for="point">分钟</label>
                    </el-col>
     
       </el-row>


<el-col :span="7">

        <el-button type="primary" @click="insertLabel ()" icon="el-icon-search"
            >添加</el-button>
     </el-col>
       </el-row>

    </el-dialog>

 <el-dialog title="修改标签" :visible.sync="showDialogVisible" width="50%">

    <el-row :gutter="20">
           <el-col :span="4">
        <label for="answer">地点:</label>
                    </el-col>
            <el-col :span="16">
        <label >{{nowlabel.address}}
          </label>
            </el-col>
            </el-row>


    <el-row :gutter="20">
           <el-col :span="4">
        <label for="answer">路况类型:</label>
                    </el-col>
            <el-col :span="16">
        <el-select v-model="nowlabel.type">
            <el-option v-for="ntype in typelist" 
            :label="ntype" 
            :key="ntype"
            :value="ntype"/>
          </el-select>
            </el-col>
            </el-row>



              <el-row :gutter="20">
           <el-col :span="4">
        <label for="answer">通行情况:</label>
                    </el-col>
            <el-col :span="4">

	    <el-button :class="[flag===0?yes:no]" @click="chooseEmer(0)">{{pass1}}</el-button>
      </el-col>
      <el-col :span="4">
	    <el-button :class="[flag===1?yes:no]" @click="chooseEmer(1)">{{pass2}}</el-button>

            </el-col>
            </el-row>

      <el-row :gutter="20">
           <el-col :span="6">
        <label for="point">提醒其他人需要注意前方路况的时间:</label>
                    </el-col>
            <el-col :span="4">
        <el-input v-model="nowlabel.time" placeholder='0'>
          </el-input>
          </el-col>
          <el-col :span="4">
        <label for="point">分钟</label>
                    </el-col>
     
       </el-row>

<el-row  type="flex" justify="end">
<el-col :span="7">

        <el-button type="primary" @click="editLabel ()" icon="el-icon-search"
            >修改</el-button>
     </el-col>
       </el-row>

    </el-dialog>

  </div>
</template>

<script>
export default {
  data: function() {
      let self = this;
    return {
      map:null,
      // 查询条件
      queryInfo: {
        id: '',
        currentPage: 1,
        title: '',
        starttime: null,
        endtime: null
      },
      // 时间起始
      timeRange: ['',''],
      // 标签列表
      labelList: [],
      passlist:["无法通行","影响通行",''],
      typelist:["拥堵","事故","障碍物","封路","修路","其它","求助",''],
      selecttype:'',
      selectpass:'',
      selectaddress:'',

      newpoint:'',
      newaddress:'浙江省杭州市xx区xx街道xxx(输入坐标自动显示)',
      newtype:'',
      newpass:'无法通行',
      newtime:'',
      showDialogVisible: false,
      newDialogVisible: false,

      flag:0,
      yes:"yes",
      no:"no",
      pass1:'无法通行',
      pass2:'影响通行',
      nowlabel:{},

      searchOption: {
            city: '杭州',
            citylimit: false
          },

        total: 0,
        zoom:16,
        center: [120.199538,30.261412],
        lng: 0,
        lat: 0,
        loaded: false,
        markers: [],
        markerRefs: [],
        windows: [],
        window: '',
        address:'',
        events: {
          init(o) {
                  // o 是高德地图定位插件实例
              setTimeout(() => {
                console.log(self.markerRefs);
                let cluster = new AMap.MarkerClusterer(o, self.markerRefs,{
                  gridSize: 80,
                  renderCluserMarker: self._renderCluserMarker
                });
                console.log(cluster);
              }, 1000);

          },

              click(e) {
                let { lng, lat } = e.lnglat;
                self.lng = lng;
                self.lat = lat;

                self.center = [lng,lat]
     
      AMap.plugin('AMap.Geocoder', function() {
  var geocoder = new AMap.Geocoder({
    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
    city: '全国'
  })
 
  var lnglat = [lng, lat]
  self.newpoint = lng+','+lat

  geocoder.getAddress(lnglat, function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
        // result为对应的地理位置详细信息
        console.log(result)
        self.newaddress = result.regeocode.formattedAddress
    }
　　　　　　　　})
  })
    if(self.firstclick){
            self.markers.push({
            position:[lng,lat],
        })
        self.firstclick=false
  }else{
  
    self.markers.pop()
    self.markers.push({
            position:[lng,lat],
        })

  }


          
                }

        },
        firstclick:true,
        plugin: [{
              enableHighAccuracy: true,//是否使用高精度定位，默认:true
              timeout: 100,          //超过10秒后停止定位，默认：无穷大
              maximumAge: 0,           //定位结果缓存0毫秒，默认：0
              convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
              showButton: true,        //显示定位按钮，默认：true
              buttonPosition: 'RB',    //定位按钮停靠位置，默认：'LB'，左下角
              showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
              showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
              panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
              zoomToAccuracy:true,//定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
              extensions:'all',
              pName: 'Geolocation',
              events: {
              click(e) {
              let { lng, lat } = e.lnglat;
              this.lng = lng;
              this.lat = lat;

              console.log(lng)

              // 这里通过高德 SDK 完成。
              var geocoder = new AMap.Geocoder({
                radius: 1000,
                extensions: "all"
              });        
              geocoder.getAddress([lng ,lat], function(status, result) {
                if (status === 'complete' && result.info === 'OK') {
                  if (result && result.regeocode) {
                    this.address = result.regeocode.formattedAddress;
                    console.log(this.address)
                    this.$nextTick();
                  }
                }
              });        
            }
                }
              
            },]

    }
  },
  created () {
    // 加载页面时 加载一次数据

    let _this=this;
    window.getlabel=_this.getlabel;
    window.deleteLabel = _this.deleteLabel;

    this.getLabelList()

  },

    mounted() {
      
    },

  methods: {
    handleAddNewLabel () {
      this.newDialogVisible = true
    },
    async getLabelList () {
      const { data: res } = await this.$http.get('label/alllabel')
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.labelList = res.data
      this.total = this.labelList.length
      console.log(res.data.records)


      let self = this
      let markers = []
      let windows = [];

      //let basePosition = [121.59996, 31.197646];

    for(let i =0;i<this.total;i++)
    {
        let pointt = this.labelList[i].point.split(",")
        let x= [pointt[0],pointt[1]]
        windows.push({
            position: x,

            content:`<div class="prompt">地点: ${ this.labelList[i].address }</div>
            <div class="prompt">路况类型: ${ this.labelList[i].type }</div>
            <div class="prompt">通行情况: ${ this.labelList[i].pass }</div>
            <div class="prompt">预计通行时间: ${ this.labelList[i].time } 分钟</div>
            <button onclick="getlabel(${this.labelList[i].id})"> 编辑</button> <button onclick="deleteLabel (${this.labelList[i].id})">删除</button>`,
            visible: false
          })
        markers.push({
            position:x,
             events: {
              click() {
                  self.windows.forEach(window => {
                  window.visible = false;
                  
                });
                
                self.window = self.windows[i];
               // self.window.visible = true;
                console.log(self.window)
                self.$nextTick(() => {
                  self.window.visible = true;
                });
              }

            }
        })
        
    }
    //console.log(windows)
    this.markers = markers;
     this.windows = windows;

    },

    // 根据条件 搜索标签信息
    async queryLabel () {
      const { data: res } = await this.$http.get(
        'search' + this.queryInfo.title
      )
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.labelList = []
      if (res.data !== null) this.labelList.push(res.data)
    },

    // 删除用户
    async deleteLabel (id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该标签, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((error) => error)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('label/delete/' + id)
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.$message.success('删除标签成功')
      // 重新加载一次
      this.window.visible=false
      this.getLabelList()
    },

    _renderCluserMarker(context) {
          const count = this.markers.length;

          let factor = Math.pow(context.count/count, 1/18)
          let div = document.createElement('div');
          let Hue = 180 - factor* 180;
          let bgColor = 'hsla('+Hue+',100%,50%,0.7)';
          let fontColor = 'hsla('+Hue+',100%,20%,1)';
          let borderColor = 'hsla('+Hue+',100%,40%,1)';
          let shadowColor = 'hsla('+Hue+',100%,50%,1)';
          div.style.backgroundColor = bgColor
          let size = Math.round(30 + Math.pow(context.count/count,1/5) * 20);
          div.style.width = div.style.height = size+'px';
          div.style.border = 'solid 1px '+ borderColor;
          div.style.borderRadius = size/2 + 'px';
          div.style.boxShadow = '0 0 1px '+ shadowColor;
          div.innerHTML = context.count;
          div.style.lineHeight = size+'px';
          div.style.color = fontColor;
          div.style.fontSize = '14px';
          div.style.textAlign = 'center';
          context.marker.setOffset(new AMap.Pixel(-size/2,-size/2));
          context.marker.setContent(div)
        },


    async search () {
      let startdate = this.timeRange[0]
      let enddate = this.timeRange[1]
      const { data: res } = await this.$http.post(
        'label/search',
        { 'endtime': enddate,
          'starttime': startdate,
          'type': this.selecttype,
          'pass':this.selectpass,
          'address':this.selectaddress }, {
          headers: {
            'content-type': 'application/json',
            'X-Request-With': 'XMLHttpRequest',
            'token': window.sessionStorage.getItem('token')
          }
        }
      )
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.labelList = []
      this.labelList = res.data
      this.total = this.labelList.length

      let self = this
      let markers = []
      let windows = []

    console.log(this.labelList)

    for(let i =0;i<this.total;i++)
    {
        let pointt = this.labelList[i].point.split(",")
        let x= [pointt[0],pointt[1]]

        windows.push({
            position: x,
            content:`<div class="prompt">地点: ${ this.labelList[i].address }</div>
            <div class="prompt">路况类型: ${ this.labelList[i].type }</div>
            <div class="prompt">通行情况: ${ this.labelList[i].pass }</div>
            <div class="prompt">预计通行时间: ${ this.labelList[i].time } 分钟</div>
            <div class="prompt"> <button class="prompt"> 编辑</button> <button class="prompt">删除</button></div>
            `,
            visible: false
          })
        markers.push({
            position:x,
           //position: [basePosition[0] + 0.01 * index, basePosition[1]],
         //   content: '<div style="text-align:center; background-color: hsla(0, 100%, 50%, 1); height: 24px; width: 24px; border: 1px solid hsl(0, 100%, 50%); border-radius: 12px; box-shadow: hsl(0, 100%, 50%) 0px 0px 1px;"></div>',
            events: {
              click() {
                  self.windows.forEach(window => {
                  window.visible = false;
                  
                });
                
                self.window = self.windows[i];
               // self.window.visible = true;
                console.log(self.window)
                self.$nextTick(() => {
                  self.window.visible = true;
                });
              }

            }
        })
        
    }
    //console.log(windows)
    this.markers=[]
    this.markers = markers;
    this.windows=[]
    this.windows = windows;

    },

    async getlabel(id){
      var { data: res } = await this.$http.get('label/getlabel/' + id)
      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.showDialogVisible = true
      this.nowlabel = res.data

      if(this.nowlabel.pass == "无法通行"){this.chooseEmer(0)}
      else if (this.nowlabel.pass == "影响通行"){this.chooseEmer(1)}

    },

    async editLabel(){
      const { data: res } = await this.$http.post(
        'label/update',
        { 'id':this.nowlabel.id,'type': this.nowlabel.type, 'pass': this.nowlabel.pass,'address':this.nowlabel.address,'time':this.nowlabel.time }, {
          headers: {
            'content-type': 'application/json',
            'X-Request-With': 'XMLHttpRequest',
            'token': window.sessionStorage.getItem('token')
          }
        }
      )

      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.showDialogVisible = false
      this.getLabelList()
      this.window.visible=false
      return this.$message.success('修改成功')
    },

    onSearchResult(pois) {
          let latSum = 0;
          let lngSum = 0;
          if (pois.length > 0) {
            pois.forEach(poi => {
              let {lng, lat} = poi;
              lngSum += lng;
              latSum += lat;
              this.markers.push([poi.lng, poi.lat]);
            });
            let center = {
              lng: lngSum / pois.length,
              lat: latSum / pois.length
            };
            this.center = [center.lng, center.lat];
          }
        },

        chooseEmer(itype){
	    if(itype===0){
        this.flag=0 
        this.newpass = this.pass1
        this.nowlabel.pass = this.pass1
       // console.log(this.newpass)
	    }else{
        this.flag=1 
        this.newpass = this.pass2
        this.nowlabel.pass = this.pass2
     // console.log(this.newpass)
    }
    },
    async insertLabel () {

      let point = this.newpoint

      console.log(point)
      console.log(this.newtype)
      console.log(this.newpass)
      console.log(this.newtime)
      const { data: res } = await this.$http.post(
        'label/insert',
        { 'point': point, 'type': this.newtype, 'pass': this.newpass,'address':this.newaddress,'time':this.newtime }, {
          headers: {
            'content-type': 'application/json',
            'X-Request-With': 'XMLHttpRequest',
            'token': window.sessionStorage.getItem('token')
          }
        }
      )

      if (res.code !== 200) return this.$message.error('Error:' + res.message)
      this.getLabelList()
      this.newDialogVisible = false
      return this.$message.success('新建标签成功')
      

    },

  },
  filters: {

  }
}
</script>

<style lang="less" scope>
    .amap-demo {
      height: 500px;
    }

    .search-box {
      position: absolute;
      top: 25px;
      left: 20px;
    }

    .amap-page-container {
      position: relative;
    }

    .yes{
    float:left
		width:4.2rem 
		height:2rem 
		line-height:2rem 
		text-align:center
		border-radius:1rem 
		&:nth-child(1){
			margin-right:0.8rem 
    }
    
    color:blue
    }
    .no{
    float:left
		width:4.2rem 
		height:2rem 
		line-height:2rem 
		text-align:center
		border-radius:1rem 
		&:nth-child(1){
			margin-right:0.8rem 
    }
    color:black

}

</style>
